package com.ist412.pocke;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This class provides a calendar which will display all the scheduled workouts in the application.
 * <p>
 * When a Workout is selected, it will display the Workout and give the user the option to edit
 * or start the workout.
 * 
 * @author Rob C & JB
 * @version 1.0
 * 
 * TODO Create custom character for this application (using SQLite ?)
 * TODO Override GridAdapter to display custom calendar
 */
public class CalendarActivity extends Activity implements OnClickListener {
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Remove title & Make fullscreen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
	    setContentView(R.layout.activity_calendar);
	    
	    MainActivity.loadData();
	    
	    // Setup navigation
        ImageView imgProfile 	= (ImageView) findViewById(R.id.navigation_imgProfile);
        ImageView imgCalendar 	= (ImageView) findViewById(R.id.navigation_imgCalendar);
        ImageView imgWorkout	= (ImageView) findViewById(R.id.navigation_imgWorkout);
        ImageView imgExercises	= (ImageView) findViewById(R.id.navigation_imgExercise);
        ImageView imgSettings	= (ImageView) findViewById(R.id.calendar_imgSettings);
        ImageView imgBack		= (ImageView) findViewById(R.id.calendar_imgBack);
        
        imgProfile.setOnClickListener(this);
        imgCalendar.setEnabled(false);
        imgCalendar.setImageResource(R.drawable.calendar_icon_trans_dark);
        // TODO Set this through R.color
        imgCalendar.setBackgroundColor(MainActivity._BG_BLUE);
        imgWorkout.setOnClickListener(this);
        imgExercises.setOnClickListener(this);
        imgSettings.setOnClickListener(this);
	    imgBack.setOnClickListener(this);
        
	} // end onCreate()
	
	@Override
	public void onResume() {
		super.onResume();
		MainActivity.loadData();
		showWorkouts();
	}
	
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
			case R.id.navigation_imgProfile:
				intent = new Intent(this, ProfileActivity.class);
				startActivity(intent);
				break;
			case R.id.navigation_imgWorkout:
				intent = new Intent(this, WorkoutActivity.class);
				startActivity(intent);
				break;
			case R.id.navigation_imgExercise:
				intent = new Intent(this, ExerciseActivity.class);
				startActivity(intent);
				break;
			case R.id.calendar_imgBack:
				finish();
				break;
			case R.id.calendar_imgSettings:
				intent = new Intent(this, SettingsActivity.class);
				startActivity(intent);
				break;
		}
	} // end onClick()
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	protected final void showWorkouts() {
		// Display Workouts in relevant sections
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		RelativeLayout.LayoutParams rlp;
		RelativeLayout rly, rlyClone;
		LinearLayout lly;
		TextView tv;
		ImageView img, imgEdit, imgDelete, imgStart;
		boolean[] schedule, hasSchedule;
		Workout w;
		View v;
		int childCount;
		
		// LinearLayouts for each day's workouts
		LinearLayout llySunday, llyMonday, llyTuesday, llyWednesday, llyThursday, llyFriday, llySaturday;
		
		// Container to hold relative layouts
		ArrayList<RelativeLayout> sundayW, mondayW, tuesdayW, wednesdayW, thursdayW, fridayW, saturdayW;
		
		// Container to hold relative layers for each day
		ArrayList<ArrayList<RelativeLayout>> dayWorkouts = new ArrayList<ArrayList<RelativeLayout>>();
		
		// Container to hold LinearLayouts for each day
		ArrayList<LinearLayout> dayLLY = new ArrayList<LinearLayout>();
		
		// Default
		sundayW 	= new ArrayList<RelativeLayout>();
		mondayW 	= new ArrayList<RelativeLayout>();
		tuesdayW 	= new ArrayList<RelativeLayout>();
		wednesdayW 	= new ArrayList<RelativeLayout>();
		thursdayW 	= new ArrayList<RelativeLayout>();
		fridayW 	= new ArrayList<RelativeLayout>();
		saturdayW 	= new ArrayList<RelativeLayout>();		
		
		// Fill workout container
		dayWorkouts.add(sundayW);
		dayWorkouts.add(mondayW);
		dayWorkouts.add(tuesdayW);
		dayWorkouts.add(wednesdayW);
		dayWorkouts.add(thursdayW);
		dayWorkouts.add(fridayW);
		dayWorkouts.add(saturdayW);
		
		// Get LinearLayouts
		llySunday 		= (LinearLayout) findViewById(R.id.calendar_llySundayExercises);
		llyMonday 		= (LinearLayout) findViewById(R.id.calendar_llyMondayExercises);
		llyTuesday 		= (LinearLayout) findViewById(R.id.calendar_llyTuesdayExercises);
		llyWednesday 	= (LinearLayout) findViewById(R.id.calendar_llyWednesdayExercises);
		llyThursday 	= (LinearLayout) findViewById(R.id.calendar_llyThursdayExercises);
		llyFriday 		= (LinearLayout) findViewById(R.id.calendar_llyFridayExercises);
		llySaturday 	= (LinearLayout) findViewById(R.id.calendar_llySaturdayExercises);
		
		// Fill day container
		dayLLY.add(llySunday);
		dayLLY.add(llyMonday);
		dayLLY.add(llyTuesday);
		dayLLY.add(llyWednesday);
		dayLLY.add(llyThursday);
		dayLLY.add(llyFriday);
		dayLLY.add(llySaturday);
		
		// Used to determine if a day has a scheduled workout
		hasSchedule = new boolean[] { false, false, false, false, false, false, false };
		
		for (int i = 0; i < dayLLY.size(); i++) {
			dayLLY.get(i).removeAllViews();
		}
		
		// Find workouts scheduled on days
		for (int i = 0; i < MainActivity._workouts.size(); i++) {
			// Shortcut workout
			w = MainActivity._workouts.get(i);
			
			//Log.e("Workout AE","Workout slot: " + i + " | Workout name: " + w.getName() + " | Workout scheduled: " + w.isScheduled());
			
			// Don't continue if no schedule provided
			if (!w.isScheduled()) {
				/*// Default text view with warning
				tv = new TextView(this);
				tv.setText("No Workouts Scheduled");
				rly = new RelativeLayout(this);
				rly.addView(tv);
				dayLLY.get(i).addView(rly);*/
				continue;
			}
			
			// Show on relevant days
			schedule = w.getSchedule();
			
			//Log.e("Calendar","dayLLY.size(): " + dayLLY.size() + " | schedule.length: " + schedule.length);
			
			for (int j = 0; j < schedule.length; j++) {
				//Log.e("Calendar","Schedule[" + j + "]:" + Boolean.toString(schedule[j]));
				if (schedule[j]) {
					hasSchedule[j] = true;
					//Log.e("Calendar","Inflating list_item, i: " + i);
					inflater.inflate(R.layout.list_item, dayLLY.get(j));
					lly = dayLLY.get(j);
					childCount = lly.getChildCount();
					
					v = lly.getChildAt((childCount - 1));
					
					tv = (TextView) v.findViewById(R.id.listitem_txtTitle);
					tv.setText(w.getName());
					tv.setGravity(Gravity.CENTER);
					
					img = (ImageView) v.findViewById(R.id.listitem_imgStart);
					img.setOnClickListener(new WorkoutStarter(i));
					
				} // end if (scheduled)
			} // end for j (iterate through schedule days)
		} // end for i (iterate through workouts)
		
		// Fill in days without schedules
		for (int i = 0; i < hasSchedule.length; i++) {
			if (!hasSchedule[i]) {
				inflater.inflate(R.layout.spinner_item, dayLLY.get(i));
				lly = dayLLY.get(i);
				
				tv = new TextView(this);
				tv.setText("No Workouts Scheduled");
				lly.addView(tv);
			}
		}
		
	} // end showWorkouts()
	
	
	/**
	 * Creates new ProgressActivity to begin the workout
	 * 
	 * @param _wslot	Slot of Workout to use
	 * 
	 * TODO Use Workout.id instead of _wslot
	 */
	protected final void startWorkout(int _wslot) {
		Intent i = new Intent(this, ProgressActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		i.putExtra("workoutslot", _wslot);
		startActivity(i);
	}
	
	/**
	 * Utility function to show Toast. Set to Toast.LENGTH_SHORT
	 * @param text	Text to display in the toast
	 */
	protected final void showToast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Utility class to start the Workout activity
	 * 
	 * @author Rob
	 * @Version 1.0
	 */
	private class WorkoutStarter implements OnClickListener {
		
		private int _wslot;
		
		/**
		 * @param wslot	Workout slot number to start
		 * 
		 * TODO Use SQLite Workout.id to target a Workout to start
		 */
		public WorkoutStarter(int wslot) {
			_wslot = wslot;
		}
		
		@Override
		public void onClick(View v) {
			Intent i = new Intent(CalendarActivity.this, ProgressActivity.class);
			i.putExtra("workoutslot", _wslot);
			startActivity(i);
		}
		
	} // end inline class WorkoutStarter
	
} // end class CalendarActivity
